/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.huawei.housekeeper.gateway.service;

import com.alibaba.fastjson.JSON;
import com.huawei.housekeeper.commonutils.constants.BaseConstant;
import com.huawei.housekeeper.commonutils.result.Result;
import com.huawei.housekeeper.gateway.enums.ErrorCode;
import com.huawei.housekeeper.gateway.util.HeaderUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 权限校验失败的处理服务
 */
@Component
public class AuthCheckFailHandlerService extends HttpBasicServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException au) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        HttpHeaders headers = response.getHeaders();
        headers.add(BaseConstant.Header.HEADERS_TYPE, "application/json; charset=UTF-8");
        HeaderUtil.setHeaders(headers);
        Result<Object> result = Result.createResult(ErrorCode.FORBIDDEN);
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(result));
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
}